<template>
  <n-grid cols="1" responsive="screen" class="-mt-5">
    <n-grid-item>
      <n-list>
        <n-list-item>
          <template #suffix>
            <n-button type="primary" text @click="updatePass">修改</n-button>
          </template>
          <n-thing title="账户密码">
            <template #description
              ><span class="text-gray-400">修改账户密码</span></template
            >
          </n-thing>
        </n-list-item>
        <n-list-item>
          <template #suffix>
            <n-button type="primary" text @click="updateEmail">修改</n-button>
          </template>
          <n-thing title="绑定邮箱">
            <template #description
            ><span class="text-gray-400">已绑定邮箱：{{form.email}}</span></template
            >
          </n-thing>
        </n-list-item>
        <n-list-item>
          <template #suffix>
            <n-button type="primary" text @click="updateMobile">修改</n-button>
          </template>
          <n-thing title="绑定手机">
            <template #description
              ><span class="text-gray-400">已绑定手机号：{{form.phone}}</span></template
            >
          </n-thing>
        </n-list-item>
      </n-list>
    </n-grid-item>
  </n-grid>
  <n-modal v-model:show="mobileEditValidate">
    <n-card style="width: 500px;" title="修改手机号码" :bordered="false" size="huge">
      <n-form
        :model="mobileEditForm"
        :rules="mobileRules"
        ref="mobileFormRef"
        label-placement="left"
        :label-width="100"
      >
        <n-form-item label="手机号码" path="phone">
          <n-input v-model:value="mobileEditForm.phone" @change="hasEditMobile" placeholder="请输入新手机号"/>
        </n-form-item>
        <n-form-item path="smsCode" label="验证码">
          <n-input
            v-model:value="mobileEditForm.smsCode"
            placeholder="请输入短信验证码"
          >
          </n-input>
          <n-button style="margin-left: 5px;" :disabled="btnDisabled" @click="sendMsgCode">{{btnText}}</n-button>
        </n-form-item>
      </n-form>
      <template #footer>
        <div style="display: flex; justify-content: flex-end;">
          <n-space>
            <n-button type="primary" :loading="submitLoading" @click="submitMobileForm">提交</n-button>
            <n-button @click="()=>(mobileEditValidate=false)">关闭</n-button>
          </n-space>
        </div>
      </template>
    </n-card>
  </n-modal>
  <n-modal v-model:show="emailEditValidate">
    <n-card style="width: 500px;" title="修改邮箱" :bordered="false" size="huge">
    <n-form
      ref="emailFormRef"
      label-placement="left"
      :model="emailEditForm"
      :rules="emailFormRules"
      :label-width="100"
    >
      <n-form-item path="email" label="邮箱">
        <n-input v-model:value="emailEditForm.email" @change="hasEditEmail" placeholder="请输邮箱地址">
        </n-input>
      </n-form-item>
      <n-form-item path="emailCode" label="验证码">
        <n-input
          v-model:value="emailEditForm.emailCode"
          placeholder="请输邮箱验证码"
        >
        </n-input>
        <n-button style="margin-left: 5px;" :disabled="btnDisabled" @click="getEmailCode">{{emailText}}</n-button>
      </n-form-item>
    </n-form>
      <template #footer>
        <div style="display: flex; justify-content: flex-end;">
          <n-space>
            <n-button type="primary" :loading="submitLoading" @click="submitMobileEmail">提交</n-button>
            <n-button @click="()=>(emailEditValidate=false)">关闭</n-button>
          </n-space>
        </div>
      </template>
    </n-card>
  </n-modal>
  <check-password ref="checkPassMobile" @on-success="checkSuccessMobile"/>
  <check-password ref="checkPassEmail" @on-success="checkSuccessEmail"/>
  <edit-password ref="checkPasswd"/>
</template>
<script lang="ts">
import CheckPassword from '@/views/password/check-password.vue'
import EditPassWord from '@/views/password/edit-password.vue'
import {defineComponent,ref,onMounted} from 'vue'
import {useUserStore} from "@/store/modules/user";
import {useMessage} from 'naive-ui';
import EditPassword from "@/views/password/edit-password.vue";
import { PersonOutline,LockClosedOutline} from '@vicons/ionicons5';
import {sendSmsCode,checkMobile,editMobile,sendEditEmailCode,editEmail} from "@/api/system/user";

export default defineComponent({
  name:'SafetySetting',
  components:{
    EditPassword,
    CheckPassword,
    EditPassWord,
    PersonOutline,
    LockClosedOutline
  },
  emits:['on-success'],
  setup(props,{emit}){
    const message=useMessage();
    const checkPassMobile=ref(null);
    const checkPassEmail=ref(null);
    const checkPasswd=ref(null);
    const form=ref({});
    const count=ref(60);
    const useStore=useUserStore();
    const emailEditValidate=ref(false);
    const emailBtnDisabled=ref(false);
    const emailCount=ref(60);
    const emailFormRef=ref(null);
    const mobileEditForm=ref({
      mobile:'',
      smsCode:'',
    });
    const emailEditForm=ref({
      mobile:'',
      emailCode:'',
    });
    const mobileEditValidate=ref(false);
    const btnDisabled=ref(false);
    const btnText=ref('获取验证码');
    const emailText=ref('获取验证码');
    const submitLoading=ref(false);
    const mobileFormRef=ref(null);
    const mobileRules={
      phone: { required: true, trigger: 'blur',
        validator: (rule, value) => {
          const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
          return new Promise((resolve, reject) => {
            if(value==''){
              btnDisabled.value=true;
              reject(Error('请输入手机号码'))
            }else if(!reg.test(value)){
              btnDisabled.value=true;
              reject(Error('请输入正确的手机号码'))
            }else{
              checkMobile({mobile:value,oldMobile:''}).then(res=>{
                if(res){
                  btnDisabled.value=true;
                  reject(Error('手机号码已存在'));
                }else{
                  btnDisabled.value=false;
                  resolve()
                }
              })
            }
          })
        }
      },
      smsCode:{required:true,message:'请输入验证码',trigger:'blur'},
    };
    const downEmailCount=()=>{
      if(emailCount.value==0){
        emailText.value='获取验证码';
        emailBtnDisabled.value=false;
        emailCount.value=60
        return ;
      }else{
        emailText.value=emailCount.value+"秒后重试"
        emailCount.value--;
        emailBtnDisabled.value=true;
      }
      setTimeout(()=>{
        downEmailCount();
      },1000);
    };
    const emailFormRules={
      email:{required:true,message:'请输入邮箱地址',trigger:'blur',
        validator: (rule, value) => {
          return new Promise((resolve, reject) => {
            const regEmail=/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
            if(value==null) {
              reject(Error('请输入邮箱'))
            }else if(!regEmail.test(value)){
              reject(Error('邮箱格式不正确'))
            }else{
              resolve()
            }
          })
        }
      },
      emailCode:{required:true,message:'请输入邮箱验证码',trigger: 'blur'},
    }
    const checkSuccessMobile=()=>{
      mobileEditValidate.value=true;
    }
    const checkSuccessEmail=()=>{
      emailEditValidate.value=true;
    };
    const getEmailCode=()=>{
      if(emailEditForm.value.email==''){
         message.error('请输入邮箱地址');
         return;
      }
      emailBtnDisabled.value=true;
      sendEditEmailCode(emailEditForm.value.email).then(res=>{
        message.success('发送成功');
        downEmailCount();
      })
    }
    const updateEmail=()=>{
      checkPassEmail.value.showModal=true;
      checkPassEmail.value.password='';
    };
    const init=()=>{
      let info = useStore.info;
      form.value=info;
    }
    const hasEditMobile=()=>{
        if(form.value.phone===mobileEditForm.value.phone){
          btnDisabled.value=true;
        }else{
          btnDisabled.value=false;
        }
    };
    const hasEditEmail=()=>{
      if(form.value.email===emailEditForm.value.email){
        emailBtnDisabled.value=true;
      }else{
        emailBtnDisabled.value=false;
      }
    }
    const updatePass=()=>{
      checkPasswd.value.showModal=true;
    };
    const sendMsgCode=()=>{
      if(mobileEditForm.value.phone==''){
         message.error('请输入手机号码');
         return;
      }
      btnDisabled.value=true;
      sendSmsCode(mobileEditForm.value.phone).then(res=>{
        message.success('发送成功')
        downCount();
      })
    }
    const updateMobile=()=>{
      checkPassMobile.value.password='';
      checkPassMobile.value.showModal=true;
    }
    onMounted(()=>{
      init();
    })
    const submitMobileForm=()=>{
      mobileFormRef.value.validate((errors)=>{
        if(!errors){
            editMobile(mobileEditForm.value).then(res=>{
              if(res){
                message.success('修改成功');
                form.value.phone = mobileEditForm.value.phone;
                mobileEditValidate.value=false;
                emit('on-success');
              }
            })
        }
      })
    };
    const submitMobileEmail=()=>{
      emailFormRef.value.validate((errors)=>{
        if(!errors){
          editEmail(emailEditForm.value).then(res=>{
            if(res){
              message.success('修改成功');
              form.value.email = emailEditForm.value.email;
              emailEditValidate.value=false;
              emit('on-success');
            }
          })
        }
      })
    }
    const downCount=()=>{
      if(count.value==0){
        btnText.value='获取验证码';
        btnDisabled.value=false;
        count.value=60
        return ;
      }else{
        btnText.value=count.value+"秒后重试"
        count.value--;
        btnDisabled.value=true;
      }
      setTimeout(()=>{
        downCount();
      },1000);
    }
    return {
      checkPassMobile,
      updateEmail,
      checkSuccessMobile,
      checkSuccessEmail,
      updatePass,
      checkPassEmail,
      checkPasswd,
      form,
      mobileEditForm,
      mobileEditValidate,
      btnDisabled,
      btnText,
      sendMsgCode,
      submitMobileForm,
      emailEditForm,
      submitLoading,
      mobileRules,
      emailEditValidate,
      updateMobile,
      mobileFormRef,
      emailText,
      getEmailCode,
      emailFormRules,
      hasEditEmail,
      hasEditMobile,
      submitMobileEmail,
      emailFormRef
    }
  }
})
</script>
